package com.example.demo.utils;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

public class BeanUtils {

    /**
     * @Title: beanCopyWithIngore
     * @Description: source中的非空属性复制到target中，但是忽略指定的属性，有些属性是不可修改的
     * @param: @param <T>
     * @param: @param source
     * @param: @param target
     * @param: @param ignoreProperties
     * @return: void
     * @throws
     */
    public static <T> void beanCopyWithIngore(T source, T target, String... ignoreProperties) {
        String[] pns = getNullAndIgnorePropertyNames(source, ignoreProperties);
        org.springframework.beans.BeanUtils.copyProperties(source, target, pns);
    }
    /**
     * @Title: getNullAndIgnorePropertyNames
     * @Description: 处理不需要进行赋值的指定属性
     * @param: @param source
     * @param: @param ignoreProperties
     * @param: @return
     * @return: String[]
     * @throws
     */
    public static String[] getNullAndIgnorePropertyNames(Object source, String... ignoreProperties) {
        Set<String> emptyNames = getNullPropertyNameSet(source);
        for (String s : ignoreProperties) {
            emptyNames.add(s);
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * @Title: getNullPropertyNameSet
     * @Description: 将空值属性进行Set赋值
     * @param: @param source
     * @param: @return
     * @return: Set<String>
     * @throws
     */
    public static Set<String> getNullPropertyNameSet(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null || "null".equals(srcValue)) {
                emptyNames.add(pd.getName());
            }
        }
        return emptyNames;
    }
    private static  AtomicInteger inc = new AtomicInteger();
    private static void increase() {
        inc.getAndIncrement();
    }

}
